package com.yq.cp.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class HttpUtil {

    private static HttpUtil httpUtil;
    private static RestTemplate restTemplate;

    private HttpUtil() {

    }

    private static ClientHttpRequestFactory requestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(10000);
        return factory;
    }

    public static HttpUtil builder() {
        if (httpUtil == null) {
            httpUtil = new HttpUtil();
            HttpUtil.restTemplate = new RestTemplate(requestFactory());
        }
        return httpUtil;
    }

    /**
     * Get 请求
     *
     * @param url url
     * @return resp
     */
    public String doGet(String url) {
        return restTemplate.getForEntity(
                url,
                String.class
        ).getBody();
    }

    /**
     * Post XML 请求
     *
     * @param url  url
     * @param data data
     * @return resp
     */
    public String doPostXML(String url, String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        return restTemplate.postForEntity(
                url,
                new HttpEntity<>(data, headers),
                String.class
        ).getBody();
    }

    /**
     * Post JSON 请求
     *
     * @param url  url
     * @param data data
     * @return resp
     */
    public String doPostJson(String url, String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return restTemplate.postForEntity(
                url,
                new HttpEntity<>(data, headers),
                String.class
        ).getBody();
    }



}
